<template>
  <div class='num-wrap'>
    <el-form :model='ruleForm' :rules='rules' ref='numForm'>

      <el-form-item prop='phone'>
        <el-input placeholder='请输入手机号码' v-model='ruleForm.phone'>
          <i slot='prefix' class='el-icon-phone'> </i>
        </el-input>
      </el-form-item>

      <el-form-item prop='code'>
        <el-row :gutter='18'>
              <el-col :span='18'>
                <el-input  placeholder='填入验证码' v-model='ruleForm.code'>
                <i slot='prefix' class='el-icon-tickets'> </i>
                </el-input>
              </el-col>
              <el-col :span='6'>
                <el-button @click=sendCode() :disabled='disabled'>{{btnText}}</el-button>
              </el-col>
        </el-row>  
      </el-form-item>

      <el-form-item>
        <el-button style='width:100%' @click='loginSucc'>登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
name:'phonelogin',
data(){
       //rule：验证规则 value：输入框值 callback：回调函数
  // eslint-disable-next-line no-unused-vars
  let checkPhone =(rule,value,callback)=>{
      if(!value){
        return callback(new Error('手机号不能为空'))
      }else{
        let reg=/^1[3|4|5|6|7|8][0-9]\d{8}$/
        if(reg.test(value)){
          callback()
        }
        else{
          return callback(new Error('请输入正确的手机号'))
        }

      }
    }
  return{
    rules:{
      phone:[
        {
         
        validator:checkPhone,
        trigger:'change'
        }
      ],
      code:[
        {
          required:true,
          message:'验证码不能为空',
          trigger:'blur'
        }
      ]
      
    },
    disabled:false,
    btnText:'发送验证码',
    time:0

}
},
props:{
  ruleForm:{
    type:Object,
    required:true
  },
  countdown:{
    type:Number,
    default:60
  }
},
methods:{
  sendCode(){
// 手机号必须填入正确才能发送验证码
this.$refs.numForm.validateField('phone',errorMessage=>{
 if(errorMessage){
   this.$message.error(errorMessage)
 // eslint-disable-next-line no-empty
 }else{
   //1.时间开始倒数
   //2.按钮进入禁用状态
   //3.如果倒计时结束 按钮恢复可用状态 按钮文字变成重新发送 把倒计时时间重置
   //4.倒计时过程中，按钮文字变成xx秒后重新发送
   // eslint-disable-next-line no-unused-vars
   let timer =setInterval(()=>{
     this.time--
     // eslint-disable-next-line no-undef
     this.btnText=`${this. time}s后重新发送`
     this.disabled=true
     if(this.time===0){
       this.disabled=false
       this.btnText='重新发送'
       this.time=this.countdown
       clearInterval(timer)
     }
   },1000)
   this.$emit('send')
 }
 
})

},
loginSucc(){
  this.$refs.numForm.validate((valid)=>{
    if(valid){
      this.$emit('submit')
    }else{
      this.$emit('errHandle')
    }
  })
 }
},
mounted(){
  this.time=this.countdown
}
}
</script>

<style>
.num-wrap{
  width:600px;
  margin-top:30px;
  margin-left:30px
}

</style>